<!-- 登录界面 -->
<template>
    <div class="shell">
        <!-- 顶部logo区域 -->
        <div class="top">
            <div class="logo">
                <img src="@/assets/CodeRealm.png" />
            </div>
            <div class="l-name">
                <span>AgriHub</span><sup>®</sup>
            </div>
        </div>
        <!-- 中部内容区域 -->
        <div class="middle">
            <!-- 左侧表单 -->
            <div class="m-left">
                <div class="inp">
                    <span style="color: #38eb0b" class="label">用账户名称登录</span>
                    <input v-model="Form.username" spellcheck="false" type="text">
                </div>
                <div class="inp">
                    <span class="label">密码</span>
                    <input v-model="Form.password" type="password" @keyup.enter="login">
                </div>
                <div class="memory" @click="keepAccount">
                    <Select class="sel-icon" :class="{ white: !memory }" />
                    <span>记住我</span>
                </div>
                <div class="bnt">
                    <button @click="login" :disabled="isSubmitting">{{ isSubmitting ? '登录中...' : '登录' }}</button>
                </div>
            </div>
            <!-- 右侧二维码 -->
            <div class="m-right">
                <img src="@/assets/qrcode.png" alt="">
                <span class="r-bottom">通过二维码浏获取 AgriHub 网站</span>
            </div>
        </div>
        <!-- 底部跳转 -->
        <div class="bottom">
            <div>
                <span>还没有 AgriHub 账户？</span>
                <span style="margin-left: 6px;cursor: pointer;" class="underline" @click="toReg">创建免费账户</span>
            </div>
        </div>
    </div>
</template>

<script setup>
// 引入element的加载动画
import { ElLoading } from 'element-plus'
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/stores'
// 使用 inject 获取全局提供的 axios 实例
const $axios = inject('$axios')
const $tools = inject('$tools')
const $elaxios = inject('$elaxios')

const router = useRouter()
const mainStore = useMainStore()

const memory = ref(localStorage.getItem('memory') === 'true')
const Form = ref({
    username: '',
    password: '',
})

function keepAccount() {
    memory.value = !memory.value
    localStorage.setItem('memory', memory.value)
    
    // 如果选择记住账户，则保存当前输入的账户和密码
    if (memory.value && Form.value.username) {
        const userSecret = {
            account: Form.value.username,
            pwd: Form.value.password
        }
        localStorage.setItem('userSecret', JSON.stringify(userSecret))
    } else {
        // 如果取消记住账户，则清除保存的账户信息
        localStorage.removeItem('userSecret')
    }
    // console.log(memory.value)
}

// 页面跳转函数
function toReg() {
    router.push('/reg')
}

// 防抖标志
const isSubmitting = ref(false)

// 登录函数
async function login() {
    // 防止重复提交
    if (isSubmitting.value) {
        return
    }
    // 表单验证
    if (!Form.value.username || !Form.value.password) {
        $tools.alertMsg('账号或密码不能为空', 'error')
        return
    }
    isSubmitting.value = true

    const query = {
        user_name: Form.value.username,
        user_pwd: Form.value.password,
    }

    const loadingInstance = ElLoading.service({
        text: '登录中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        const response = await $axios.post('/user/login', query)
        // console.log(response.data);
        if (response.data.code === 200) {
            // 保存登录状态
            localStorage.setItem('token', response.data.data.token)
            mainStore.saveUserData(response.data.data);
            
            // 如果选择记住账户，则保存当前登录的账户和密码
            if (memory.value) {
                const userSecret = {
                    account: Form.value.username,
                    pwd: Form.value.password
                }
                localStorage.setItem('userSecret', JSON.stringify(userSecret))
                localStorage.setItem('memory', 'true')
            }
            
            $tools.alertMsg('登录成功', 'success')
            setTimeout(() => {
                sessionStorage.setItem('navView', 4)
                router.push('/home')
                isSubmitting.value = false
            }, 1000)
        } else {
            $tools.alertMsg(response.data.msg || '登录失败，请稍后重试','error',2000)
            isSubmitting.value = false
        }
    } catch (error) {
        console.error('登录错误:', error)
        $tools.alertMsg(response.data.msg || '登录失败，请稍后重试','error',2000)
        isSubmitting.value = false
    } finally {
        loadingInstance.close()
        
    }
}

// 获取ip定位
function getDeviceLocation() {
    // 使用百度地图API获取位置(地区ID)
    $elaxios.get('/map_api/location/ip', {
        params: {
            ak: 'DYgNaKmEbTUCSiZ8d3YsWK7ah7C2vv9F',
        }
    }).then((response) => {
        getWeather(response.data.content.address_detail.adcode)
        // console.log(response.data)
    }).catch(function (error) {
        console.log(error);
    });

}

// 获取天气情况
function getWeather(id) {
    // 使用百度地图API获取天气，通过地区ID获取
    $elaxios.get('/map_api/weather/v1/', {
        params: {
            ak: 'DYgNaKmEbTUCSiZ8d3YsWK7ah7C2vv9F',
            data_type: 'all',
            district_id: id,
        }
    }).then((response) => {
        mainStore.saveWeather(response.data.result);
    }).catch(function (error) {
        console.log(error);
    });

}

// 页面渲染前获得数据
if (memory.value) {
    const secret = JSON.parse(localStorage.getItem('userSecret') || '{}');
    // console.log(secret)
    Form.value.username = secret.account || '';
    Form.value.password = secret.pwd || '';
}

// 页面挂载后执行
getDeviceLocation();
</script>

<style lang="less" scoped>
.white {
    color: #ffffff !important;
}

.underline {
    text-decoration: underline;
}

.shell {
    padding: 0px 40px 30px 0px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    background-color: #fbfbfb;
    width: 710px;
    margin: 0 auto;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    margin-top: -100px;

    .top,
    .middle,
    .identity,
    .bottom {
        padding-left: 40px;
    }
    // 顶部样式
    .top {
        display: flex;
        align-items: center;
        color: #E0E1E6;
        margin-top: 20px;
        margin-bottom: 6px;

        .logo {
            img {
                width: 44px;
                height: 44px;
            }
        }

        .l-name {
            background: linear-gradient(to right bottom, rgb(77, 220, 58), rgb(147, 248, 88));
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            margin-left: 4px;

            span {
                font-size: 24px;
                font-weight: bold;
                letter-spacing: 2px;
            }

            sup {
                font-size: 9px;
                vertical-align: top;
            }
        }
    }
    // 中部样式
    .middle {
        display: flex;
        justify-content: space-between;

        .m-left,
        .m-right {
            display: flex;
            flex-direction: column;
        }

        .m-left {
            .inp {
                text-align: left;
                display: flex;
                flex-direction: column;
                margin-top: 11px;

                .label {
                    font-size: 12px;
                    color: #AFAFAF;
                    margin-bottom: 3px;
                }

                input {
                    background-color: #f9f9f9;
                    width: 384px;
                    height: 38px;
                    border-radius: 2px;
                    color: #222;
                    outline: none;
                    border: 1px solid #ddd;
                    text-indent: 10px;
                    font-size: 14px;

                    // &:hover {
                    //     background-color: #393C44;
                    // }
                }
            }

            .memory {
                margin-top: 10px;
                display: flex;
                align-items: center;
                cursor: pointer;
                user-select: none;

                span {
                    vertical-align: middle;
                    font-size: 12px;
                    color: #AFAFAF;
                }

                .sel-icon {
                    margin-right: 6px;
                    width: 15px;
                    height: 15px;
                    padding: 2px;
                    color: #32353C;
                    border: 1px solid #999;
                    border-radius: 2px;
                }

            }

            .bnt {
                margin-top: 12px;

                button {
                    cursor: pointer;
                    width: 384px;
                    height: 44px;
                    color: #fff;
                    border: none;
                    outline: none;
                    font-size: 15px;
                    border-radius: 2px;
                    // background-image: linear-gradient(to right, #06BFFF, #2D73FF);
                    background-image: linear-gradient(to right, rgb(77, 220, 58), rgb(147, 248, 88));
                    &:hover {
                        background-image: linear-gradient(to right, rgb(77, 220, 58), rgb(58, 220, 99) 30%,rgb(147, 248, 88));
                    }
                    // &:hover {
                    //     background-image: linear-gradient(to right, #06BFFF, #08BAFF 30%, #2D73FF);
                    // }
                }
            }
        }

        .m-right {
            margin-left: 30px;
            margin-top: 10px;

            img {
                width: 180px;
                height: 180px;
                padding: 20px;
                border-radius: 4px;
                background-color: #f2f2f2;
            }

            .r-bottom {
                font-size: 12px;
                color: #666;
                margin-top: 6px;
            }
        }
    }

    .bottom {
        margin-top: 20px;

        span {
            font-size: 12px;
            color: #666;
        }
    }
}
</style>